<?php
/**
 * admin service file Created by PhpStorm.
 * User: wumengmeng
 * Date: 2019/09/05
 * Time: 09:36
 */

namespace Modules\SmallApi\Service;

use HiCommon\Repository\RepairstoreGoodsRepository;
use HiCommon\Repository\RepairstoreTypeRepository;
use HiCommon\Repository\OrderRepairstoreRepository;
use HiCommon\Repository\ShopRepository;
use HiCommon\Repository\UsersRepository;
use HiCommon\Service\PayService;
use HiCommon\Service\PayYanSongDaService;
use Modules\SmallApi\Service\CouponService;
use HiCommon\Repository\CollectRepository;
use HiCommon\Repository\OrderRepairstoreAppriseRepository;
use Modules\SmallApi\Service\UserService;
use HiCommon\Service\PublicService;
class RepairstoreGoodsService
{

    /**
     * 获取分页数据
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function get_list($option)
    {
        try {
            if (!$option['lon'] || !$option['lat']) {
                return hello_error('经纬度参数错误');
            }

            $data = RepairstoreGoodsRepository::small_get_list($option);
            $data = list_page_data($data);

            foreach ($data['data'] as $key => &$value) {
                $value['type_id'] = $value['type']['id'];
                $value['type'] = $value['type']['title'];
                $value['shop_id'] = $value['shop']['id'];
                $value['shop_name'] = $value['shop']['name'];
                $value['shop_logo'] = $value['pic'][0]['picurl'] ?? $value['shop']['logo'];

                $city = str_replace(',', '', $value['shop']['area_name']['mername']);

                $value['shop_address'] = $city . ' ' . $value['shop']['address'];

                unset($value['shop']);
                unset($value['pic']);
            }

            return hello_success('成功', $data);
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 查询一条数据
     *
     * @param int $n_id
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function get_one(int $n_id)
    {
        try {
            $n_id = (int)$n_id;
            if ($n_id <= 0) {
                hello_error('数据ID不能为空');
            }

            //查询
            $arr_option['with'] = ['shop'];
            $res = RepairstoreGoodsRepository::get_one($n_id, $arr_option)->toarray();

            if (empty($res)) {
                return hello_error('查询失败');
            }

            $is_collect = false;
            if (!empty(small_api_user_id())) {
                $arr_where = ['x_id' => $n_id, 'user_id' => small_api_user_id(), 'type' => 2];
                $count = CollectRepository::get_count_by_where((array)$arr_where);
                if ($count > 0) {
                    $is_collect = true;
                }
            }

            if (stripos($res['detail'], '<img src="/')) {
                $res['detail'] = str_replace('src="/', 'src="https://xdminiapi.chxing.cn/', $res['detail']);
            }
            if (stripos($res['detail'], '<img src="')) {
                $infoed = str_replace('/>', ' align="center" width="100%"/>', $res['detail']);
            }

            $detail = [
                'id' => $res['id'],
                'banner' => $res['pic'],
                'name' => $res['name'],
                'shop_id' => $res['shop']['id'],
                'title' => $res['shop']['name'],
                'shop_address' => $res['address'],
                'price' => $res['price'],
                'detail' => $infoed,
                'fuwu' => $res['fuwu'],
                'price_indication' => $res['price_indication'],
                'is_collect' => $is_collect,
            ];
            return hello_success('查询成功', $detail);
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     *    获取维修种类
     */
    public function get_repairstore_type()
    {
        try {
            $data = RepairstoreTypeRepository::get_all(['status' => 1], ['id', 'title']);

            return hello_success('成功', $data);
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 立即购买生成订单
     */
    public function buy_goods_now(array $data)
    {
        try {
            $uid = small_api_user_id();
            if (!$uid) {
                return hello_error('请登录');
            }
            if (empty($data['repairstore_goods_id'])) {
                return hello_error('商品id不能为空');
            }
            if (empty($data['shop_id'])) {
                return hello_error('门店id不能为空');
            }

            $data['user_id'] = $uid;
            $isHave = self::check_is_have($data);
            if ($isHave) {
                return hello_success('已有订单', $isHave);//返回已经创建的订单数据
            }

            //创建订单
            $data['order_number'] = random_order_sn('OR');
            $goods = RepairstoreGoodsRepository::get_goods_price((int)$data['repairstore_goods_id']);//获取商品价格
            if ($goods) {
                $data['goods_type'] = $goods->type;
                $data['goods_name'] = $goods->name;
                $data['order_price'] = $goods->price;
            } else {
                return hello_error('商品不存在');
            }

            $addRes = OrderRepairstoreRepository::add_one($data);
            $shop = ShopRepository::get_shop((int)$data['shop_id']);

            $result = array();
            if ($addRes && $shop) {
                $result['shop_logo'] = $shop->logo['full_src'];
                $result['shop_name'] = $shop->name;
                $result['shop_address'] = $shop->address;
                $result['order_id'] = $addRes->id;
                $result['order_price'] = $addRes->order_price;
                $result['order_number'] = $addRes->order_number;
                $result['goods_name'] = $addRes->goods_name;
                $result['goods_num'] = 1;
            } else {
                return hello_error('订单创建失败');
            }

            return hello_success('订单创建成功', $result);
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 检查该商品是否已经有订单
     */
    public function check_is_have($data)
    {
        $map = [
            'user_id' => (int)$data['user_id'],
            'shop_id' => (int)$data['shop_id'],
            'repairstore_goods_id' => (int)$data['repairstore_goods_id'],
            'pay_status' => 0,
            'status' => 0
        ];

        $isHave = OrderRepairstoreRepository::check_is_have($map);//检查该订单是否已经存在
        if ($isHave) {
            $detail = $isHave->toarray();
            $result['shop_logo'] = $detail['shop']['logo']['full_src'];
            $result['shop_name'] = $detail['shop']['name'];
            $result['shop_address'] = $detail['shop']['address'];
            $result['order_id'] = $detail['id'];
            $result['order_price'] = $detail['goods']['price'];
            $result['order_number'] = $detail['order_number'];
            $result['goods_name'] = $detail['goods_name'];
            $result['goods_num'] = 1;

            return $result;
        }

        return null;
    }

    /**
     * 支付订单
     */
    public function repair_pay_order($data)
    {
        try {
            $uid = small_api_user_id();
            //$uid = 15;
            if (!$uid) {
                return hello_error('请登录');
            }

            if (empty($data['order_id'])) {
                return hello_error('订单id不能为空');
            }

            if (empty($data['order_number'])) {
                return hello_error('订单编号不能为空');
            }

            if (empty($data['pay_price'])) {
                return hello_error('实付金额不能为空');
            }

            $map = ['id' => $data['order_id'], 'user_id' => $uid, 'order_number' => $data['order_number']];
            //支付金额验证
            $order = OrderRepairstoreRepository::find_one($map);
            if (empty($order)) {
                return hello_error('订单不存在');
            }

            if ($order->pay_status == 0) { //支付金额验证
                if (empty($data['coupons_id'])) {
                    if ($order->order_price != $data['pay_price']) {
                        return hello_error('实际支付金额有误！');
                    }
                } else {
                    $arrInput = ['goods_id' => $order->repairstore_goods_id, 'coupon_id' => $data['coupons_id'], 'type' => 1];
                    $coupon = PublicService::goods_coupon_imputed_price((array)$arrInput); //使用优惠券后的价格
                    // dd($coupon);
                    if ($coupon['state'] == 0) {
                        if ($coupon['data']['price'] != $data['pay_price']) {
                            return hello_error('实际支付金额有误！');
                        }
                    } else {
                        return hello_error($coupon['msg']);
                    }

                    $upData = [
                        'coupons_id' => $data['coupons_id'] ?? null,
                        'user_coupons_id' => $data['user_coupons_id'] ?? null,
                        'coupon_price' => $coupon['data']['coupon_price']
                    ];

                    OrderRepairstoreRepository::edit_pay_status((array)$map, (array)$upData);
                }

                //微信支付成功
                $s_out_trade_no = $data['order_number'];//订单编号
                $s_openid = UsersRepository::get_small_openid_by_uid($uid);//用户openid
                $n_total_fee = $data['pay_price'] * 100;// **单位：分**
                $s_body = '信达养车-维修预约单支付';
                $s_attach = 'order_repairstore';
                $s_order_type = 'wxfw';
                $result = PayService::api_wxmini_pay($s_order_type,$s_out_trade_no, $n_total_fee, $s_body, $s_openid);

                return $result;

            } else {
                return hello_error('该订单已支付，或已退款,请重新下单');
            }

        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 维修店商品订单（用户修改订单状态）
     * 修改订单状态（1取消订单，2申请退款，3确认完成-关闭订单）
     */
    public function repairOrderModifyState($data)
    {
        try {
            $order_id = intval($data['order_id']);//订单id
            $uid = intval(small_api_user_id());//用户id
            if (!$uid) {
                return hello_error('请登录');
            }

            if (empty($order_id)) {
                return hello_error('订单id不能为空');
            }

            if (empty($data['type'])) {
                return hello_error('修改类型不能为空');
            }

            $map = ['id' => $data['order_id'], 'user_id' => $uid];

            $order = OrderRepairstoreRepository::get_one_by_where((array)$map, ['field' => ['pay_status', 'status']]);
            if (empty($order->first())) {
                return hello_error('订单不存在！');
            } else {
                if ($data['type'] == '1') { //取消订单

                    if ($order->pay_status == 0 && $order->status == 0) {
                        $upData = ['status' => 2];
                        if (OrderRepairstoreRepository::edit_pay_status((array)$map, (array)$upData)) {
                            return hello_success('订单取消成功！', []);
                        } else {
                            return hello_error('订单取消失败');
                        }
                    } else {
                        return hello_error('订单状态不对，取消失败！');
                    }

                } elseif ($data['type'] == '2') {//申请退款

                    if ($order->pay_status == 1 && $order->status == 0) {
                        if (empty($data['refund_cause'])) {
                            return hello_error('申请退款原因必填');
                        }

                        $upData = ['pay_status' => 2, 'refund_cause' => $data['refund_cause'], 'apply_refund_time' => date('Y-m-d H:i:s')];
                        if (OrderRepairstoreRepository::edit_pay_status((array)$map, (array)$upData)) {
                            return hello_success('已发送退款申请，等待管理人员审核！', []);
                        } else {
                            return hello_error('申请失败！请联系商家');
                        }
                    } else {
                        return hello_error('订单状态不对，申请失败！');
                    }

                } elseif ($data['type'] == '3') {//确认完成---关闭订单
                    $upData = ['status' => 4];
                    if (OrderRepairstoreRepository::edit_pay_status((array)$map, (array)$upData)) {
                        return hello_success('操作成功！');
                    } else {
                        return hello_error('操作失败');
                    }
                } else {
                    return hello_error('修改类型错误');
                }

            }

        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     *  获取维修店的订单详情
     *  hinq 2019 09 23
     *
     **/
    public function get_repairstore_goods_detail_to_order(int $nId)
    {
        try {

            if (empty($nId)) {
                return ['state' => 1, 'msg' => '参数错误', 'data' => [], 'error' => ''];
            }
            //获取用户订单信息
            $arr_option = ['field' => ['id', 'repairstore_goods_id', 'goods_num', 'order_number', 'pay_status', 'status']];
            $order_info = OrderRepairstoreRepository::get_one_by_where((array)['id' => $nId, 'user_id' => small_api_user_id()], (array)$arr_option)->toarray();
            if (empty($order_info)) {
                return ['state' => 1, 'msg' => '订单信息获取失败', 'data' => [], 'error' => ''];
            }

            $option['field'] = ['name', 'price', 'id', 'repairstore_id'];
            $option['with'] = ['shop' => function ($query) {
                $query->with(['area_name']);
            }];

            //获取订单商品信息
            $arr_list = RepairstoreGoodsRepository::get_one((int)$order_info['repairstore_goods_id'], (array)$option)->toarray();
            if (empty($arr_list)) {
                return ['state' => 1, 'msg' => '商品信息获取错误', 'data' => [], 'error' => ''];
            }
            $temp['goods_id'] = $order_info['repairstore_goods_id'];
            $temp['goods_num'] = $order_info['goods_num'];
            $temp['order_number'] = $order_info['order_number'];
            $temp['status'] = $order_info['status'];
            $temp['pay_status'] = $order_info['pay_status'];
            $temp['id'] = $arr_list['id'];
            $temp['name'] = $arr_list['name'];
            $temp['price'] = $arr_list['price'];
            $temp['picurl'] = $arr_list['pic'][0]['picurl'];

            $city = str_replace(',', '', $arr_list['shop']['area_name']['mername']);

            $temp['shop_id'] = $arr_list['shop']['id'];
            $temp['shop_name'] = $arr_list['shop']['name'];
            $temp['shop_address'] = $city . ' ' . $arr_list['shop']['address'];
            $temp['shop_longitude'] = $arr_list['shop']['longitude'];
            $temp['shop_latitude'] = $arr_list['shop']['latitude'];

            $coupon_info = CouponService::get_my_coupon_to_goods((array)['goods_id' => $arr_list['id']]);
            $temp['coupons'] = [];
            if (!empty($coupon_info) && $coupon_info['state'] == 0) {
                $temp['coupons'] = $coupon_info['data'];
            }
            return ['state' => 0, 'msg' => 'ok', 'data' => $temp, 'error' => ''];
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }


    /**
     * 用户获取维修店服务商品列表
     */
    public function getUserOrderList($data)
    {
        $uid = small_api_user_id();//用户id
        if (!$uid) {
            return hello_error('请登录');
        }

        $arr_option['where'] = ['user_id' => $uid];
        $arr_option['with'] = ['shop', 'gtype', 'goods' => function ($query) {
            $query->with(['pic']);
        }];

        $listAll = OrderRepairstoreRepository::api_get_list($arr_option, hi_array_del_null($data))->toArray();

        $page['total'] = $listAll['total'];
        $page['per_page'] = $listAll['per_page'];
        $page['current_page'] = $listAll['current_page'];
        if ($listAll['data']) {
            $list = array();
            foreach ($listAll['data'] as $key => $item) {
                $list[] = array(
                    'order_id' => $item['id'],
                    'order_number' => $item['order_number'],
                    'shop_id' => $item['shop']['id'],
                    'shop_name' => $item['shop']['name'],
                    'goods_logo' => $item['goods']['pic'][0]['picurl']['full_src'],
                    'goods_name' => $item['goods_name'],//服务名称
                    'created_at' => $item['created_at'],
                    'order_price' => $item['order_price'],
                    'pay_status' => $item['pay_status'],
                    'status' => $item['status'],
                    'order_status' => OrderRepairstoreRepository::orderStatus($item['status'], $item['pay_status'])
                );
            }
            return hello_success('获取成功！', ['list' => $list, 'page' => $page]);
        } else {
            return hello_error('暂无数据');
        }
    }


    /**
     *  用户评论订单(维修店服务商品订单评论)
     *  hinq 2019 09 27
     *
     **/
    public function create_order_repairstore_comment(array $arr_input)
    {
        try {

            if (empty($arr_input['score'])) {
                return hello_error('评分数量不能为空');
            }
            if (!in_array($arr_input['score'], [1, 2, 3, 4, 5])) {
                return hello_error('评分数量错误');
            }
            if (empty($arr_input['order_id'])) {
                return hello_error('订单id不能为空');
            }
            if (empty($arr_input['content'])) {
                return hello_error('评价内容不能为空');
            }
            $arr_input['user_id'] = small_api_user_id();

            //获取当前订单信息
            $order_list = OrderRepairstoreRepository::get_one_by_where((array)['id' => $arr_input['order_id'], 'user_id' => $arr_input['user_id']], (array)['field' => ['shop_id', 'id', 'status', 'pay_status', 'pay_price']]);
            if (empty($order_list->first())) {
                return hello_error('只能评价自己的订单');
            }

            if ($order_list['status'] != 1 && $order_list['pay_status'] == 1) {
                return hello_error('该订单暂时不能评价');
            }

            if (empty($order_list['shop_id'])) {
                return hello_error('商家不存在');
            }
            $arr_input['shop_id'] = $order_list['shop_id'];
            $count = OrderRepairstoreAppriseRepository::get_count_by_where((array)['user_id' => $arr_input['user_id'], 'order_id' => $arr_input['order_id']]);
            if ($count >= 1) {
                return hello_error('您已经评价，请勿重复评价');
            }

            //给用户添加购买商品获得的积分
            // $arrInput['integral'] = floor($order_list['pay_price']);
            $arrInput['user_id'] = $arr_input['user_id'];    //用户id
            $arrInput['total_fee'] = $order_list['pay_price'];    //支付金额
            $arrInput['type'] = 1;
            $arrInput['order_id'] = $arr_input['order_id'];
            $arrInput['order_type'] = 3;
            $arrInput['remarks'] = '评论订单获得积分';
            $res1 = PublicService::user_integral_change((array)$arrInput);
            if ($res1['state'] == 1) {
                return hello_error($res1['msg']);
            }

            //修改评论的订单状态
            $arr_where['id'] = $arr_input['order_id'];
            $arr_where['status'] = 3;
            $res = OrderRepairstoreRepository::edit_one((array)$arr_where);
            if (empty($res)) {
                return hello_error('评价失败');
            }

            //添加评论信息
            $res = OrderRepairstoreAppriseRepository::add_one((array)$arr_input);
            if (empty($res)) {
                return hello_error('评价失败');
            }

            return hello_success('评价成功');
        } catch (\Exception $exception) {
            DB::rollBack();
            return hello_error('失败', [], $exception->getMessage());
        }
    }


}